<?php

namespace app\models;

use app\models\tableModel\AdminUserModel;
use Yii;
use yii\base\Model;
use yii\debug\controllers\UserController;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    public $verifyCode; // 验证码

    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {

        if (!$this->hasErrors()) {

            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError(400, '账号密码不匹配');
                return false;
            }

            // 如果 status == -1 禁用 就不能登录
            if($user['status'] == -1)
            {
                $this->addError($attribute, '帐号已被禁用');
                return false;
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(),
                $this->rememberMe ? 3600 * 24 * 30 : 20);
        }
        return false;
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool
     */
    public function appLogin()
    {
        if ($this->validate()) {
            return true;
        }

        return false;
    }

    /**
     * Finds user by [[username]]
     * @return array|AdminUserModel
     */
    public function getUser()
    {

        // 先来根据 用户匹配登陆
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

//        // 再来根据手机号
//        if ($this->_user === false || !$this->_user) {
//            $this->_user = User::findByPhone($this->username);
//        }

        return $this->_user;
    }
}
